#include "ctableview.h"
#include "ctableviewstyle.h"

#include <DPaletteHelper>
#include <DStyle>
#include <QTimer>
#include <QVBoxLayout>

CTableView::CTableView(QWidget *parent)
    : QTableView(parent)
    , m_delegate(nullptr)
    , m_horizontalHeaderView(nullptr)
{

    m_delegate= new CTableViewDelegate(this);

    setItemDelegate(m_delegate);
    setShowGrid(false);
    setStyle(new CTableViewStyle);
    setMouseTracking(true);
    setAttribute(Qt::WA_Hover, true);
    setSelectionBehavior(QAbstractItemView::SelectionBehavior::SelectRows);
    verticalHeader()->setVisible(false);

    m_horizontalHeaderView = new CTableHeaderView(Qt::Orientation::Horizontal, this);
    setHorizontalHeader(m_horizontalHeaderView);

    // 设置背景透明
    QPalette pa = palette();
    pa.setColor(QPalette::Base, Qt::transparent);
    setPalette(pa);

    installEventFilter(this);
}

CTableView::~CTableView()
{
}

void CTableView::setHeaderBgTransparent(bool transparent)
{
    DPalette dpa;
    if (transparent) {
        dpa = DPaletteHelper::instance()->palette(m_horizontalHeaderView);
        dpa.setColor(DPalette::ColorRole::Base, Qt::transparent);
    } else {
        dpa = DPaletteHelper::instance()->palette(this);
    }
    DPaletteHelper::instance()->setPalette(m_horizontalHeaderView, dpa);
}

bool CTableView::eventFilter(QObject *obj, QEvent *event)
{
    if (this == obj) {
        if (QEvent::Type::HoverMove == event->type()) {
            updateCurrentHoveringIndex();
        }
    }
    return QTableView::eventFilter(obj, event);
}

void CTableView::updateCurrentHoveringIndex()
{
    QPoint logicMousePoint = viewport()->mapFromGlobal(QCursor::pos());

    QModelIndex currentHoveringIndex = indexAt(logicMousePoint);

    int currentRow = currentHoveringIndex.row();
    int currentCol = currentHoveringIndex.column();
    if (currentRow!= m_currentHoveringIndex.row() ||
        currentCol != m_currentHoveringIndex.column()) {
//        qInfo() << Q_FUNC_INFO << currentHoveringIndex.row() << currentHoveringIndex.column();
        m_currentHoveringIndex = currentHoveringIndex;
        m_delegate->setCurrentHoveringIndex(m_currentHoveringIndex);

        // 用于触发代理paint函数
        int rightestCol = model()->columnCount() - 1;
        Q_EMIT model()->dataChanged(model()->index(currentRow, 0),
                                    model()->index(currentRow, rightestCol), {0});
    }
}
